<template>
  <div style="background:#f7f7f7;">
    <div v-if="urlSecond" class="header" :class="{ 'header-add': getOpened }">
      <div class="header-main">
        <div class="header-main-left">
          <i
            class="el-icon-arrow-left"
            style="font-size: 20px; margin-right: 5px; cursor: pointer"
            @click="$router.push({ name: 'Dashboard' })"
          />
          <span>编辑变量模块</span>
        </div>
        <el-button type="primary" size="default">创建成功</el-button>
      </div>
    </div>
    <!-- 这里就是变量管理封装的内容 -->
    <!-- 左边部分 -->
    <div class="management">
      <!-- 左边目录 -->
      <div ref="catalog" class="catalog">
        <Tree
          :catalog="catalog"
          :directory-list="directoryList"
          @addCatalogue="addCatalogue"
          @addChildCatalogue="addChildCatalogue"
          @newsGetTemplateQuestionList="newsGetTemplateQuestionList"
          @removeUsualVariable="removeUsualVariable"
          @detailCatalogue="detailCatalogue"
          @recomposeCatalogue="recomposeCatalogue"
        />
        <!-- 添加目录 -->
        <!-- <div class="catalogue-add pointer" @click="addCatalogue">+</div> -->
      </div>

      <!-- 右边详情 -->
      <div ref="details" class="Details">
        <!-- 提示 -->
        <div style="heigh:20px;width:100%;">
          <div style="width:100%;text-align:center;font-size:14px;">拖动调整变量</div>
        </div>
        <Details
          :directory-list="directoryList"
          :fullscreen-loading="fullscreenLoading"
          :fixedmodules="fixedmodules"
          :submit-to-save="SubmitToSave"
          :unable-redirection="unableRedirection"
          :change-directorydo-not="changeDirectorydoNot"
          @sendDirectoryList="sendDirectoryList"
          @ClickTriggered="ClickTriggered"
          @RetrieveData="RetrieveData"
          @unableRedirectionFalse="unableRedirectionFalse"
        />
      </div>

    </div>
    <el-dialog
      title="提示"
      :visible.sync="set_bianji_pattern"
      append-to-body
      width="30%"
      style="margin-top: 150px"
      @close="newcountermandList"
    >
      <span>是否保存已录入数据？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="newcountermandList">取 消</el-button>
        <el-button @click="set_pattern_data">不 保 存</el-button>
        <el-button type="primary" @click="baocun_data">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 获取模板下目录列表  获取目录下模块及变量 // 设置模板-含新增/编辑/删除/排序-目录/模块/变量
import {
  getTemplateDirectoryList,
  getTemplateQuestionList,
  setTemplateItemAdnQuestion
} from '@/api/stencil'
// 详情展示页
import Details from './components/Details.vue'
// 目录
import Tree from './components/Tree.vue'
export default {
  components: {
    Details,
    Tree
  },
  data() {
    return {
      set_bianji_pattern: false, // 提示用户是否保存数据
      addCatalogue_index: 0, // 新增目录下标
      database_id: '', // 数据库id
      template_id: '', // 模板id
      catalog: [], // 目录
      defaultProps: {
        children: 'items',
        label: 'item_name',
        disabled: 'disabled'
      },
      directoryList: [], // 存放用户点击左侧目录拿到的数据
      urlSecond: '', // 判断自定义模板
      fixedmodules: 0, // 回到顶部
      fullscreenLoading: false, // loading
      firstnewConfindid: '', // 定义的id
      SubmitToSave: 0, // 提交保存
      unableRedirection: true, // 定义一个数据 父传子 如果发生改变就说明不能跳转
      changeDirectorydoNot: 0 // 切换目录 不保存
    }
  },
  computed: {
    getOpened() {
      return this.$store.state.app.sidebar.opened
    },
    newmodified() {
      return this.$store.state.management.modified
    }

  },
  async created() {
    this.database_id =
      this.$store.getters.database_id === ''
        ? this.$store.state.user.userInfo.id
        : this.$store.getters.database_id
    this.template_id =
      this.$store.getters.template_id !== ''
        ? this.$store.getters.template_id
        : this.$store.state.user.getSelect.template_id === undefined
          ? this.$store.state.user.userInfo.basicTemplateId
          : this.$store.state.user.getSelect.template_id
    // this.database_id = this.$store.getters.database_id
    // this.template_id = this.$store.getters.template_id === '' ? this.$store.state.user.getSelect.template_id : this.$store.getters.template_id
    console.log(this.database_id, this.template_id)
    const res = {
      database_id: this.database_id,
      template_id: this.template_id
    }
    const data = await getTemplateDirectoryList(res)
    this.catalog = data.data.data
    console.log('结果2', this.catalog)
    // 将数据存到vuex中
    this.$store.dispatch('management/setListManagement', this.catalog)
    if (this.$store.state.management.userCatalogID !== '') {
      this.newGetTemplateQuestionList(
        this.database_id,
        this.template_id,
        this.$store.state.management.userCatalogID
      )
    } else {
      if (this.catalog[0].items.length >= 1) {
        this.newGetTemplateQuestionList(
          this.database_id,
          this.template_id,
          this.catalog[0].items[0].item_id
        )
        // 将用户第一次的目录id存起来
        this.$store.dispatch(
          'management/setUserCatalogID',
          this.catalog[0].item_id
        )
      } else {
        // 将用户第一次的目录id存起来
        this.$store.dispatch(
          'management/setUserCatalogID',
          this.catalog[0].item_id
        )
        this.newGetTemplateQuestionList(
          this.database_id,
          this.template_id,
          this.catalog[0].item_id
        )
      }
    }

    // this.newGetTemplateQuestionList(this.database_id, this.template_id, this.catalog[0].items[0].item_id)
    // console.log('``````````````````````````````````````', this.$route)
    this.urlSecond = this.$route.query.url
  },
  methods: {
    // details传递过来更新directoryList的数据
    sendDirectoryList(e) {
      this.directoryList = e
    },
    // 修改数据
    unableRedirectionFalse(e) {
      console.log('改变unableRedirection值不然跳转', e)
      this.unableRedirection = e
    },
    // 用户点击取消
    newcountermandList() {
      // 用户点击取消
      this.set_bianji_pattern = false
      this.fullscreenLoading = false
      this.SubmitToSave = 0
      // this.$store.dispatch('management/setSetmodified', false)
    },
    // 点击保存
    async  baocun_data() {
      console.log('点击保存', this.unableRedirection)
      // 需要保存数据
      this.SubmitToSave = 1
      // this.SubmitToSave = 0
      // 如果用户点击确定
      var z
      if (z) {
        clearTimeout(z)
      }

      z = setTimeout(() => {
        if (this.unableRedirection) {
          this.newConfind(this.firstnewConfindid)
          this.CancelTheSave()
          console.log('this.unableRedirection', this.unableRedirection)
        }
      }, 1000)

      this.set_bianji_pattern = false
      this.fullscreenLoading = false
      this.unableRedirection = true
    },
    // 点击不保存
    set_pattern_data() {
      this.changeDirectorydoNot = 1
      this.$store.dispatch('management/setSetmodified', false)
      const z = setTimeout(() => {
        this.CancelTheSave()
        // 点击不保存切换数据
        this.newConfind(this.firstnewConfindid)
        this.fullscreenLoading = false
        this.set_bianji_pattern = false
        clearTimeout(z)
        this.changeDirectorydoNot = 0
      }, 300)
    },
    // 目录数据变化请求接口
    // 新增目录发请求
    recomposeCatalogue(data) {
      this.CatalogueConnector(data, '')
    },
    async CatalogueConnector(data, item_id) {
    //  拼接数据CatalogueConnector
      const res = {
        database_id: this.database_id,
        template_id: this.template_id,
        data: data === '' ? '' : JSON.stringify(data),
        del_arr: item_id === '' ? '' : {
          item_arr: [item_id],
          question_arr: ''
        },
        quote_template_id: this.$store.state.user.userInfo.basicTemplateId
      }
      const list = await setTemplateItemAdnQuestion(res)
      if (list.data.code === 0) {
        // 重新获取数据
        this.$message.error(list.data.msg)
      } else if (list.data.code === 1) {
        this.$message.success(list.data.msg)
      } else {
        this.$message.error(list.data.msg)
      }
      // 重新获取目录
      const newres = {
        database_id: this.database_id,
        template_id: this.template_id
      }
      const catalog = await getTemplateDirectoryList(newres)
      console.log(catalog)
      this.catalog = catalog.data.data
      this.newDirectory()
      this.$forceUpdate()
      console.log('list', list)
    },
    // 删除目录
    async  detailCatalogue(item) {
      console.log('删除目录呀', item, this.$store.state.management.managementitem_id)
      // 然后在判断用户的id是否为0

      // 判断是否在当前页面
      if (item.item_id === this.$store.state.management.managementitem_id) {
        // 如果进来这里说明是在当前页面
        // 判断当前页面是否还有数据
        if (this.directoryList.length !== 0) {
          return this.$message.error('目录下存在数据,禁止删除')
        }
      } else {
        if (item.has_child) {
          return this.$message.error('目录下存在数据,禁止删除')
        }
      }
      this.catalog.forEach((catalog, index) => {
        if (catalog.item_id === item.item_id) {
          this.catalog.splice(index, 1)
        }
      })
      // 这种可以直接删除
      // 先把当前的id存到vuex  deletCatalogue
      // if (this.$store.state.management.deletCatalogue.length >= 1) {
      //   var z = this.$store.state.management.deletCatalogue
      //   z.push(item.item_id)
      //   console.log('zzzzzz', z)
      //   this.$store.dispatch('management/setDeletCatalogue', z)
      // } else {
      //   this.$store.dispatch('management/setDeletCatalogue', [item.item_id])
      // }
      // 调用删除数据、
      this.CatalogueConnector('', item.item_id)
      // 判断用户是否删除自身
      console.log('判断用户是否删除自身', this.$store.state.management.userCatalogID, item.item_id)
      if (this.$store.state.management.userCatalogID === item.item_id) {
        if (this.catalog[this.catalog.length - 1].items.length >= 1) {
          this.newGetTemplateQuestionList(
            this.database_id,
            this.template_id,
            this.catalog[this.catalog.length - 1].items[0].item_id
          )
          // 将用户第一次的目录id存起来
          this.$store.dispatch(
            'management/setUserCatalogID',
            this.catalog[this.catalog.length - 1].item_id
          )
        } else {
        // 将用户第一次的目录id存起来
          this.$store.dispatch(
            'management/setUserCatalogID',
            this.catalog[this.catalog.length - 1].item_id
          )
          this.newGetTemplateQuestionList(
            this.database_id,
            this.template_id,
            this.catalog[this.catalog.length - 1].item_id
          )
        }
      } else {
        // this.newGetTemplateQuestionList(
        //   this.database_id,
        //   this.template_id,
        //   this.$store.state.management.userCatalogID
        // )
      }
    },
    RetrieveData() {
      // 重新获取数据
      this.newGetTemplateQuestionList(
        this.database_id,
        this.template_id,
        this.$store.state.management.managementitem_id
      )
    },
    // 添加一级目录
    addCatalogue(index) {
      console.log('添加目录')
      // 递增名称下标
      this.addCatalogue_index = this.addCatalogue_index + 1
      let data = {}
      data = {
        create_time: 1631150119,
        invalid_parameter1: true,
        invalid_parameter2: false,
        edit_status: true,
        item_id: 0,
        item_key: 'specimen&613960303bf26',
        item_name: '新增目录' + this.addCatalogue_index,
        items: [],
        parent_id: 0,
        relation_id: 0,
        status: 1,
        template_id: 51,
        weight: 1

      }
      // const z = setTimeout(() => {
      const catalog = [...this.catalog]
      catalog.splice(index + 1, 0, data)
      this.catalog = catalog
      // clearTimeout(z)
      // }, 700)

      // this.catalog = [...this.catalog, ...data]
    },
    // 添加二级目录
    addChildCatalogue(index, data) {
      console.log(index, data)
      // const z = setTimeout(() => {
      const catalog = this.catalog
      catalog[index].items.push(data)
      // clearTimeout(z)
      // }, 700)
    },
    // 取消保存
    CancelTheSave() {
      this.$store.dispatch('management/setModuleSelected', [])
      // 清空删除数据
      this.$store.dispatch('management/setDeleteMessages', [])
      // 清空删除目录信息
      this.$store.dispatch('management/setDeletCatalogue', [])
    },
    // 确定保存
    async establish() {
      console.log('点击被触发')
      // 拿到vuex中数据
      const data =
        this.$store.state.management.moduleSelected.length === 0
          ? ''
          : this.$store.state.management.moduleSelected
      // if (data.length === 0) {
      //   return this.$message.error('请添加模块或者变量')
      // }
      // 获取需要删除的目录
      const item_arr =
        this.$store.state.management.deletCatalogue.length === 0
          ? ''
          : this.$store.state.management.deletCatalogue
      // 获取需要删除的内容
      const delArr =
        this.$store.state.management.deleteMessages.length === 0
          ? ''
          : this.$store.state.management.deleteMessages
      console.log('data', data, delArr)
      const NEWdel = {
        item_arr: item_arr,
        question_arr: delArr
      }
      let newdelarrs = '0'
      if (NEWdel.item_arr === '' && NEWdel.question_arr === '') {
        console.log('进来了')
        newdelarrs = '1'
      }
      console.log('NEWdel', NEWdel)
      console.log('data', data, delArr)
      // 组合数据
      const datas = {
        database_id: this.database_id,
        template_id: this.template_id,
        quote_template_id: this.$store.state.user.userInfo.basicTemplateId,
        data: JSON.stringify(data),
        del_arr: newdelarrs === '0' ? NEWdel : ''
      }
      await setTemplateItemAdnQuestion(datas)
      // console.log('resss', res)
      // 请求成功之后清空vuex数据
      // await this.$message.success('保存成功')
      this.$store.dispatch('management/setModuleSelected', [])
      // 清空删除数据
      this.$store.dispatch('management/setDeleteMessages', [])
      // 清空删除目录信息
      this.$store.dispatch('management/setDeletCatalogue', [])
      // this.$forceUpdate()
    },
    // 这里是确定的回调
    newConfind(e) {
      this.fixedmodules = Math.round(Math.random() * 100000)
      this.$store.dispatch('management/setSetmodified', false)
      // 点击确定就是保存数据。
      this.newGetTemplateQuestionList(this.database_id, this.template_id, e)
      // 用户每次点击这里都需要将用户点击的目录的id存起来
      this.$store.dispatch('management/setUserCatalogID', e)
      this.SubmitToSave = 0
    },
    // 提示用户有数据没保存询问用户是否保存
    newopen(e) {
      this.fullscreenLoading = true
      this.set_bianji_pattern = true
      this.firstnewConfindid = e
      // this.$confirm('当前页面的修改未保存，是否确认操作？', '未保存', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     // 如果用户点击确定
      //     this.newConfind(e)
      //     this.CancelTheSave()
      //     this.$message({
      //       type: 'success',
      //       message: '已取消保存!'
      //     })
      //   })
      //   .catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消'
      //   })
      // })
    },
    // 需要删除二级目录的id
    removeUsualVariable(e) {
      console.log('需要删除二级目录的id', e)
      // 删除二级目录需要知道删除的二级目录下面是否有内容 如果有就不能删除
      console.log('this.directoryList', this.directoryList)
      if (this.directoryList.length >= 1) {
        return this.$message.error('目录下存在数据，禁止删除')
      }
      // 如果没存在数据 就可以删除
      // 将需要删除的数据存到vuex
      // this.$store.dispatch('management/setDeletCatalogue', [e])
      // 调用删除数据、
      this.CatalogueConnector('', e)
      // 让数据不在页面显示
      this.catalog.forEach((catalog, i) => {
        // console.log('catalog', catalog)
        if (catalog.items) {
          catalog.items.forEach((items, index) => {
            if (items.item_id === e) {
              // 进来说明就是需要删除的数据2
              // item = {}
              console.log('进来了', items)
              this.catalog[i].items.splice(index, 1)
              if (this.catalog[i].items.length === 0) {
                this.$store.dispatch('management/setManagementitemId', this.catalog[i].item_id)
              } else {
                this.$store.dispatch('management/setManagementitemId', this.catalog[i].items[0].item_id)
              }
            }
          })
        }
      })
      console.log(this.catalog)
      this.$forceUpdate()
      // 重新调用数据
      this.newGetTemplateQuestionList(this.database_id, this.template_id, this.$store.state.management.managementitem_id)
    },
    // 子元素传递告诉调用父元素
    newsGetTemplateQuestionList(e) {
      this.fullscreenLoading = true // loading
      console.log('父元素接收到子元素的id并且发送请求', e, this.$store.state.management.modified, this.newmodified, !this.newmodified)
      // 判断vuex中是否有数据 如果有就需要提升用户数据没保存
      const moduleSelected = this.$store.state.management.moduleSelected
      const deletCatalogue = this.$store.state.management.deletCatalogue
      const deleteMessages = this.$store.state.management.deleteMessages
      console.log('判断vuex中是否有数据 如果有就需要提升用户数据没保存', moduleSelected, deletCatalogue, deleteMessages)
      if (this.$store.state.management.managementitem_id === e) {
        // 如果相等就结束
        console.log('相等了')
        this.fullscreenLoading = false
        return
      }
      // 判断用户需要修改的id是否等于当前的id
      if (
        moduleSelected.length !== 0 ||
        deletCatalogue.length !== 0 ||
        deleteMessages.length !== 0 ||
        this.newmodified
      ) {
        // 进来这里说明用户存有数据不能跳转其他目录
        // 弹出弹窗给用户提示
        this.newopen(e)
        return
      }
      if (e === 0) {
        console.log('当id为0的时候就创建一个新的数据')
      }

      this.newGetTemplateQuestionList(this.database_id, this.template_id, e)
      this.fixedmodules = Math.round(Math.random() * 100000)
      // 用户每次点击这里都需要将用户点击的目录的id存起来
      this.$store.dispatch('management/setUserCatalogID', e)
    },
    // 新建目录
    newDirectory() {
      console.log(this.directoryList, '新增目录', this.catalog)
      // this.directoryList = [
      //   // {
      //   // item_id: 0,
      //   // item_name: '新增模块',
      //   // relation_id: 0,
      //   // show_status: 1,
      //   // second_item: []
      //   // }
      // ]
      // this.$store.dispatch('management/setOptionDirectory', this.directoryList)
      // 将数据存到vuex中
      this.$store.dispatch('management/setListManagement', this.catalog)
      console.log('listManagement', this.catalog)
    },
    // 这里就是用户点击保存之后的值
    async ClickTriggered() {
      this.fullscreenLoading = true // loading
      // 判断存起来的id是不是0
      // if (this.$store.state.management.managementitem_id === 0) {
      console.log('重新获取目录')
      const res = {
        database_id: this.database_id,
        template_id: this.template_id
      }
      const data = await getTemplateDirectoryList(res)
      this.catalog = data.data.data
      // const item_id = ''
      console.log('结果2', this.catalog, this.catalog[this.catalog.length - 1], this.catalog)
      // if(this.catalog[this.catalog.length-1].items.length === 0){
      //       item_id =
      // }
      this.newGetTemplateQuestionList(this.database_id, this.template_id, this.$store.state.management.managementitem_id)
      // }
    },

    async handleNodeClick(data) {
      console.log(data) // 这里就是选中的数据
      // 用户点击触发之后需要判断用户点击的是否有items如果有就不做处理 如果没有在调用接口发送请求
      if (data.items) {
        if (data.items.length >= 1) {
          console.log('进来说明有items')
          return
        }
      }
      // 用户每次点击这里都需要将用户点击的目录的id存起来
      // this.$store.dispatch('management/setUserCatalogID', data.item_id)
      // 方便下次用户使用之后 可以接着用
      // 这里就是正常的调用接口
      this.newGetTemplateQuestionList(
        this.database_id,
        this.template_id,
        data.item_id
      )
    },
    // 封装获取目录下模块及变量
    async newGetTemplateQuestionList(database_id, template_id, item_id) {
      // 将获取到的item.id存到vuex中
      this.$store.dispatch('management/setManagementitemId', item_id)
      if (item_id === 0) {
        console.log('等于0哦')
        this.fullscreenLoading = false
        this.newDirectory()
        return
      }
      const res = {
        database_id,
        template_id,
        item_id,
        need: ['need_question', 'need_option', 'need_hide']
      }
      const list = await getTemplateQuestionList(res)
      console.log('拿到数据', list)
      this.directoryList = list.data.data

      // 将用户选中的模块信息也存到vuex中
      this.$store.dispatch('management/setOptionDirectory', this.directoryList)
      const z = setTimeout(() => {
        this.fullscreenLoading = false // loading
        clearTimeout(z)
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.header {
  height: 50px;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  padding: 0 20px 0 70px;
  background: #fff;
  .header-main {
    height: 50px;
    width: 100%;
    margin-bottom: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .header-main-left {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
.header-add {
  padding-left: 96px;
}
.management {
  display: flex;
  width: 80%;
  height: 100%;
  background-color: #f7f7f7;

  .catalog {
    width: 15%;
    height: 100vh;
    background-color: #fff;
    overflow: scroll;
    white-space: nowrap;
    margin-left: 20px;
    padding-bottom: 120px;
  }
  .catalogue-add {
    height: 25px;
    width: 138px;
    border: 1px solid rgba(227, 227, 227, 100);
    text-align: center;
    line-height: 25px;
    font-size: 20px;
    font-family: Roboto;
    color: #ddd;
    margin-left: 35px;
    left: 126px;
    bottom: 0;
    background: #fff;
  }
  .Details {
    flex: 1;
    height: 100vh;
    margin-left: 2%;
    overflow: scroll;
    white-space: nowrap;
    padding-bottom: 100px;
  }
}
::-webkit-scrollbar {
  width: 0 !important;
}
::-webkit-scrollbar {
  width: 0 !important;
  height: 0;
}
</style>
